package com.sitanyun.merchant.guide.view.activity;

import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.text.Editable;
import android.text.Selection;
import android.text.Spannable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.sitanyun.merchant.guide.R;
import com.sitanyun.merchant.guide.base.BaseActivity;
import com.sitanyun.merchant.guide.base.ToastUtil;
import com.sitanyun.merchant.guide.base.utils.NetworkStateUtils;
import com.sitanyun.merchant.guide.bean.LoginBean;
import com.sitanyun.merchant.guide.bean.SmsPhoneBean;
import com.sitanyun.merchant.guide.presenter.impl.LoginAPresenterImpl;
import com.sitanyun.merchant.guide.presenter.inter.ILoginAPresenter;
import com.sitanyun.merchant.guide.view.inter.ILoginAView;
import com.sitanyun.merchant.guide.weiht.AesUtil;
import com.sitanyun.merchant.guide.weiht.DateUtils;
import com.sitanyun.merchant.guide.weiht.PhoneUtils;
import com.sitanyun.merchant.guide.weiht.SharedPreferenceUtil;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 登录
 */
public class LoginActivity extends BaseActivity implements ILoginAView {


    @BindView(R.id.sms_login)
    TextView smsLogin;
    @BindView(R.id.et_login_phone)
    EditText etLoginPhone;
    @BindView(R.id.login_message)
    TextView loginMessage;
    @BindView(R.id.pasword_login)
    TextView paswordLogin;
    @BindView(R.id.login_getptone)
    TextView loginGetptone;
    @BindView(R.id.login_forgetpassword)
    TextView loginForgetpassword;
    @BindView(R.id.et_login_pass)
    EditText etLoginPass;
    @BindView(R.id.no_pas)
    ImageView noPas;
    @BindView(R.id.yes_pas)
    ImageView yesPas;
    @BindView(R.id.paswd_layout)
    LinearLayout paswdLayout;
    @BindView(R.id.login_pass_msg)
    TextView loginPassMsg;
    @BindView(R.id.tv_return)
    ImageView tvReturn;
    @BindView(R.id.tv_title_str)
    TextView tvTitleStr;
    @BindView(R.id.image_right_key)
    ImageView imageRightKey;
    @BindView(R.id.tv_right_key)
    TextView tvRightKey;
    @BindView(R.id.ff_main_layout)
    FrameLayout ffMainLayout;
    @BindView(R.id.cb_protocol)
    CheckBox cbProtocol;
    @BindView(R.id.tv_ysxy)
    TextView tvYsxy;
    @BindView(R.id.tv_ysysxy)
    TextView tvYsysxy;
    private ILoginAPresenter mILoginAPresenter;
    private String des;
    private String encrypt;
    private byte[] mBytes;
    private String enString;

    @Override
    public int getLayoutId() {
        return R.layout.activity_login;
    }

    @Override
    public void initData(Bundle savedInstanceState) {
        setFindViewById(true);
        setTitleStr("登录");
    }

    @Override
    public void initView() {
        tvReturn.setVisibility(View.GONE);
        //监听
        etLoginPhone.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                loginMessage.setVisibility(View.GONE);
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mILoginAPresenter = new LoginAPresenterImpl(this);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }


    @Override
    public <T> T request(int requestFlag) {
        return null;
    }
          //验证码登录验证手机号
    @Override
    public <T> void response(T response, int responseFlag) {
        if (responseFlag == ILoginAView.RESPONSE_ONE) {
            SmsPhoneBean smsPhoneBean = (SmsPhoneBean) response;
            if (smsPhoneBean.getCode() == 0) {
                loginMessage.setVisibility(View.GONE);
                startActivity(new Intent(LoginActivity.this, SmsLoginActivity.class).putExtra("phone", etLoginPhone.getText().toString().trim()));
             //   finish();
            } else {
                loginMessage.setVisibility(View.VISIBLE);
                loginMessage.setText(smsPhoneBean.getMsg().toString());
            }

        }
    }

    //**登录接口
    @Override
    public <T> T requestlogin(int requestFlag) {
        return null;
    }

    @Override
    public <T> void responselogin(T response, int responseFlag) {
        if (responseFlag == ILoginAView.RESPONSE_ONE) {
            LoginBean loginBean = (LoginBean) response;
            if (loginBean.getCode() == 0) {
                SharedPreferenceUtil.SaveData("phone", etLoginPhone.getText().toString().trim());
                SharedPreferenceUtil.SaveData("pswd", etLoginPass.getText().toString().trim());
                SharedPreferenceUtil.SaveData("userid", loginBean.getUser_id());
                SharedPreferenceUtil.SaveData("token", loginBean.getAccess_token());
                SharedPreferenceUtil.SaveData("nodename", loginBean.getNode_name());
                SharedPreferenceUtil.SaveData("clientid", loginBean.getS_client_id());
                SharedPreferenceUtil.SaveData("nodeid", loginBean.getNode_id());
                SharedPreferenceUtil.SaveData("tonodeid", loginBean.getTop_node_id());
                //---------------------
                SharedPreferenceUtil.SaveData("tonodename", loginBean.getTop_node_name()+"");
                SharedPreferenceUtil.SaveData("sxtoken", loginBean.getRefresh_token());
                SharedPreferenceUtil.SaveData("staffid", loginBean.getStaff_id());
                SharedPreferenceUtil.SaveData("staffname", loginBean.getStaff_name());
                SharedPreferenceUtil.SaveData("cid", loginBean.getS_client_id());
                startActivity(new Intent(LoginActivity.this, MainActivity.class)
                .putExtra("cid","null"));
                finish();
            } else {
                loginPassMsg.setVisibility(View.VISIBLE);
                loginPassMsg.setText(loginBean.getMsg());
            }

        }
    }

    /**
     * @param view
     */
    @OnClick({R.id.tv_ysxy, R.id.tv_ysysxy,R.id.sms_login, R.id.pasword_login, R.id.login_getptone, R.id.login_forgetpassword
            , R.id.yes_pas})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            //用户协议
            case R.id.tv_ysxy:
                if (DateUtils.isFastClick()) {
                    return ;
                }
startActivity(new Intent(LoginActivity.this,AgreementActivity.class).putExtra("weburl","1"));
                break;
            //用户隐私协议
                case R.id.tv_ysysxy:
                    if (DateUtils.isFastClick()) {
                        return ;
                    }
                    startActivity(new Intent(LoginActivity.this,AgreementActivity.class).putExtra("weburl","2"));
                break;

            //验证码登录
            case R.id.sms_login:

                if (!NetworkStateUtils.isNetworkConnected(this)) {
                    ToastUtil.showToast(this, "网络异常,请稍后重试");
                    // this.finish();
                    return;
                }
                //验证码登录
                if (smsLogin.getText().equals("验证码登录")) {
                    paswdLayout.setVisibility(View.GONE);
                    smsLogin.setText("验证码登录");
                    String phone = etLoginPhone.getText().toString().trim();
                    if (phone.isEmpty()) {
                        ToastUtil.showToast(LoginActivity.this, "请输入手机号码");
                        return;
                    } else if (!PhoneUtils.isMobleNo(phone)) {
                        Toast.makeText(this, "手机号格式有误", Toast.LENGTH_SHORT).show();
                        return;
                    }
                    if (!cbProtocol.isChecked()) {
                        ToastUtil.showToast(LoginActivity.this, "请同意《用户协议》及《用户隐私协议》");
                        return;
                    }
                    mILoginAPresenter.getLoginphone(etLoginPhone.getText().toString().trim());
                } else {
                    //帐号密码登录
                    String phone = etLoginPhone.getText().toString().trim();
                    if (phone.isEmpty()) {
                        ToastUtil.showToast(LoginActivity.this, "请输入手机号码");
                        return;
                    } else if (!PhoneUtils.isMobleNo(phone)) {
                        Toast.makeText(this, "手机号格式有误", Toast.LENGTH_SHORT).show();
                        return;
                    }
                    String pass = etLoginPass.getText().toString().trim();
                    if (pass.isEmpty()) {
                        ToastUtil.showToast(LoginActivity.this, "请输入登录密码");
                        return;
                    }
                    if (!cbProtocol.isChecked()) {
                        ToastUtil.showToast(LoginActivity.this, "请同意《用户协议》及《用户隐私协议》");
                        return;
                    }
                    AesUtil mAes = new AesUtil();
                    try {
                        mBytes = pass.getBytes("UTF8");
                        enString = mAes.encrypt(mBytes);//加密
                        mILoginAPresenter.getLogin(phone, enString);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }


                }
                break;
            //密码登录
            case R.id.pasword_login:

                if (smsLogin.getText().toString().equals("验证码登录")) {
                    paswdLayout.setVisibility(View.VISIBLE);
                    smsLogin.setText("登录");
                    paswordLogin.setText("使用验证码登录");
                } else {
                    paswdLayout.setVisibility(View.GONE);
                    smsLogin.setText("验证码登录");
                    paswordLogin.setText("使用密码登录");
                    loginPassMsg.setVisibility(View.GONE);
                }


                break;
            //如何获取手机号
            case R.id.login_getptone:
                if (DateUtils.isFastClick()) {
                    return ;
                }
                startActivity(new Intent(LoginActivity.this, GetPhonesActivity.class));
                break;
            //忘记密码
            case R.id.login_forgetpassword:
                if (DateUtils.isFastClick()) {
                    return ;
                }
                startActivity(new Intent(LoginActivity.this, ForgetPasswordActivity.class));
                break;

            //查看密码
            case R.id.yes_pas:
                if (etLoginPass.getInputType() == 128) {
                    //隐藏
                    etLoginPass.setInputType(129);
                    //闭眼
                    yesPas.setImageResource(R.mipmap.gonepassword);
                } else {
                    //显示
                    etLoginPass.setInputType(128);
                    //睁眼
                    yesPas.setImageResource(R.mipmap.lookpassword);
                }
                etLoginPass.postInvalidate();
                Spannable text = etLoginPass.getText();
                Selection.setSelection(text, text.length());
                break;
        }
    }


}
